<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click="$router.back()"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="loading">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-else-if="article.title">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ article.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{ article.aut_name }}</div>
          <!-- 全局过滤器来相对时间 -->
          <div slot="label" class="publish-date">
            {{ article.pubdate | relativeTime }}
          </div>
          <!-- 模板中的$event是事件参数  用户关注-->
          <!-- 当我们传递组件的数据既要使用还要修改：
          传递：props
          :isFollowd="article.is_followed"
            修改：自定义事件
          @update-is_followed="article.is_followed=$event"
           简写方式： 在组件上使用v-model
           v-model 相当于这两个的简写
            value = "article.is_followed"
            @input="article.is_followed=$event"
           -->
          <FolloWd v-model="article.is_followed" :autId="article.aut_id" />
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <!-- 文本都是html标签， 所以使用v-html来获取 -->
        <div
          class="article-content markdown-body"
          v-html="article.content"
          ref="article-content"
        ></div>
        <van-divider>正文结束</van-divider>
        <!-- 文章的评论列表 -->
        <ComMent
        @reply-click="onReply"
          :source="article.art_id"
          :list="commentList"
          @onload-success="totaCommentCount = $event.total_count"
        />
        <!-- 文章的评论列表 -->

        <!-- 底部区域 -->
        <div class="article-bottom">
          <van-button
            class="comment-btn"
            type="default"
            round
            size="small"
            @click="isShow = true"
            >写评论</van-button
          >
          <van-icon name="comment-o" :info="totaCommentCount" color="#777" />
          <!-- 收藏 -->
          <CollEct
            v-model="article.is_collected"
            class="btn-item"
            :article-id="article.art_id"
          />
          <!-- 收藏 -->
          <!-- 点赞 -->
          <LiKe
            class="btn-item"
            v-model="article.attitude"
            :article-id="article.art_id"
          />
          <!-- 点赞 -->

          <van-icon name="share" color="#777777"></van-icon>
        </div>
        <!-- /底部区域 -->
        <!-- 弹出层  发布评论-->
        <van-popup v-model="isShow" position="bottom">
          <PostComment :target="article.art_id" @post-success="onPost" />
        </van-popup>
        <!-- 弹出层 -->
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-else-if="errStatus === 404">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <!--  eslint-disable-next-line vue/valid-v-else-if -->
      <div class="error-wrap" v-else>
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="loadArticle">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>
          <!-- 评论回复 -->
   <van-popup
   v-model="isReplyShow"
    position="bottom"
    :style="{ height: '100%' }">

    <!-- 评论回复封装组件 -->
    <RePly
    v-if="isReplyShow"
    :comment="currentComment"
    @close="isReplyShow = false"
    />
   </van-popup>
      <!-- /评论回复 -->
  </div>
</template>

<script>
import { getArticleById } from '@/api/article'
import { ImagePreview } from 'vant'
import FolloWd from '@/components/followd'
import CollEct from '@/components/collect'
import LiKe from '@/components/like'
import ComMent from './components/comment-list'
import PostComment from './components/commen-post'
import RePly from './components/comment-reply'
// import { addFollw, deleteFollw } from '@/api/user'
// ImagePreview({
//   images: [
//     'https://img01.yzcdn.cn/vant/apple-1.jpg',
//     'https://img01.yzcdn.cn/vant/apple-2.jpg'
//   ],
//   // 起始位置 从0开始
//   startPosition: 0
// })
export default {
  name: 'ArticleIndex',
  components: {
    FolloWd,
    CollEct,
    LiKe,
    ComMent,
    PostComment,
    RePly
  },
  props: {
    articleId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      article: {}, // 文章详情
      loading: true, // 加载中的loading状态
      errStatus: 0, // 失败的状态码
      follwLoading: false,
      totaCommentCount: 0,
      isShow: false,
      commentList: [], // 评论列表
      isReplyShow: false,
      currentComment: {} // 当前点击回复的评论项
    }
  },
  computed: {},
  watch: {},
  // 初始调用
  created () {
    this.loadArticle()
  },
  mounted () {},
  methods: {
    async loadArticle () {
      // 重新加载一上来就让loadArticle 等于true
      this.loadArticle = true
      try {
        const { data } = await getArticleById(this.articleId)
        // 数据驱动视图不是立即的
        this.article = data.data
        // console.log('this.article', this.article.aut_id)
        // console.log('this.article', this.article)
        // 初始化图片点击预览
        // console.log(this.$refs['article-content'])

        setTimeout(() => {
          this.previewImage()
        }, 0)
        // 请求成功，关闭loading
        // this.loading = false
      } catch (err) {
        console.log('获取失败', err)
        if (err.response && err.response.status === 404) {
          this.errStatus = 404
        }
      }
      // 无论成功失败都要关闭loading，所以放在外面来
      this.loading = false
    },
    onPost (data) {
      // 关闭弹出层
      this.isShow = false
      // 将发布内容显示到列表顶部
      this.commentList.unshift(data.new_obj)
    },
    previewImage () {
      // 得到所有的img节点
      const articleContent = this.$refs['article-content']
      const imgs = articleContent.querySelectorAll('img')
      console.log(imgs)
      // 获取所有img地址
      const images = []
      imgs.forEach((img, index) => {
        images.push(img.src)
        // 给每个img注册点击事件，在处理函数中调用预览
        img.onclick = () => {
          ImagePreview({
            // 预览的图片地址数组
            images,
            // 起始位置 从0开始
            startPosition: index
          })
        }
      })
    },
    onReply (comment) {
      // console.log(comment)
      // 显示评论回复弹出层
      this.isReplyShow = true

      this.currentComment = comment
    }
    /* async onFollow () {
      this.follwLoading = true // 展示关注按钮的loading状态
      try {
        if (this.article.is_followed) {
          // 已关注,取消关注
          await deleteFollw(this.article.aut_id)
        } else {
          // 没有关注，添加关注
          await addFollw(this.article.aut_id)
        }
        // 更新视图
        this.article.is_followed = !this.article.is_followed
      } catch (err) {
        let message = '操作失败，请重试!'
        if (err.response && err.response.status === 400) {
          message = '你不能关注你自己！'
        }
        this.$toast(message)
      }
      // 因为最终都需要关闭，所有把loading状态再catch最后面
      this.follwLoading = false // 关闭关注按钮的loading状态
    } */
  }
}
</script>

<style scoped lang="less">
// 引入 github 样式
@import "./github-markdown.css";
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  /deep/ .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
